﻿using Android.Graphics.Drawables;
using Android.Graphics.Drawables.Shapes;
using Games.Common;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(ImageLabel), typeof(Games.Droid.ControlRenders.ImageLabelRender))]
namespace Games.Droid.ControlRenders
{
    class ImageLabelRender : LabelRenderer
    {
        private Android.Content.Res.Resources resources;
        public ImageLabelRender(Android.Content.Context context) : base(context)
        {
            resources = context.Resources;
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            var stack = e.NewElement as ImageLabel;
            SetBackImage(stack);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if(e.PropertyName == ImageLabel.BackImageProperty.PropertyName)
            {
                var lbl = Element as ImageLabel;
                SetBackImage(lbl);
            }
        }

        private void SetBackImage(ImageLabel lbl)
        {
            if(lbl == null)
            {
                return;
            }
            if(!string.IsNullOrWhiteSpace(lbl.BackImage))
            {
                var bitmap = new BitmapDrawable(resources, resources.GetBitmap(lbl.BackImage));
                this.Control.SetBackground(bitmap);
            }
            else
            {
                var shape = new ShapeDrawable(new RectShape());
                shape.Paint.Color = lbl.BackgroundColor.ToAndroid();
                this.Control.SetBackground(shape);
            }
        }
    }
}